<template>
  <div>
    <el-form-item label="学校图片" v-if="imageList">
      <el-upload
        class="upload-demo"
        action="http://up-z2.qiniu.com"
        :on-remove="handleRemove"
        :file-list="imageChange"
        :on-success="handleSuccess"
        :data="upToken"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-form-item>
  </div>  
</template>
<script>
import bus from '../../bus.js';
export default {
  props: {
    imageList: Array
  },
  data () {
    return {
      upToken: null,
      school_pics: []
    }
  },
  methods: {
    getToken() {
      APP.ajax('token', {}, res => {
        this.upToken = { 'token': res.data.data.token };
      })
    },
    // 删除图片
    handleRemove(file, fileList) {
      if (file.id) {
        // 如果图片带有id，则需要将id发送后台
        this.school_pics.push(file.id);
        bus.$emit('schoolPics', this.school_pics);
        bus.$emit('schoolPicUpload', fileList);
      }
    },
    handleSuccess(response, file, fileList) {
      // 上传成功，将所有的数据发送给父组件
      bus.$emit('schoolPicUpload', fileList);
    }
  },
  mounted () {
    this.getToken();
  },
  computed: {
    imageChange: function () {
      this.imageList.forEach(element => {
        if (!element.url) {
          element.url = 'http://' + element.school_pic
        }
      });
      return this.imageList;
    }
  }
}
</script>
